﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using LS.Api.Helper;
using LS.Api.Models;
using LS.Common;
using LS.Cores;
using LS.Entitys;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

namespace LS.Api.Controllers
{
    /// <summary>
    /// 用户中心
    /// </summary>
    public class UserController : APIBaseController
    {
        ISysUser userService;
        ISysNotice noticeService;
        public UserController(ISysUser repositoryUser, ISysNotice repositorySysNotice)
        {
            userService = repositoryUser;
            noticeService = repositorySysNotice;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="input">修改密码实体</param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize]
        public IHttpActionResult ChangePwd(ChangePwdInput input)
        {
            if (input == null)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "提交信息不能为空"));
            }
            if (string.IsNullOrEmpty(input.OldPassword) || string.IsNullOrEmpty(input.Password) || string.IsNullOrEmpty(input.ConfirmPassword))
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "提交信息不能为空"));
            }
            if (input.Password != input.ConfirmPassword)
            {
                return ApiJson(new ApiJsonResult(ApiResult.Fail, "新密码和确认密码不一致"));
            }

            try
            {
                var authInfo = RequestContext.RouteData.Values["auth"] as AuthInfo;

                var user = userService.GetById(authInfo.UserId);
                if (user == null)
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, "用户不存在"));
                }
                if (user.UserPwd != input.OldPassword)
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, "旧密码输入错误"));
                }
                user.UserPwd = input.Password;

                var ret = userService.Update(user);
                if (ret > 0)
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Success, "密码修改成功"));
                }
                else
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, "提交失败，请重试"));
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
            }
        }

        /// <summary>
        /// 我的通知列表
        /// </summary>
        /// <param name="pageSize">分页大小</param>
        /// <param name="pageIndex">分页索引</param>
        /// <returns>NotifyType 0=通知 1=私信 3=代办</returns>
        [HttpGet]
        [ApiAuthorize]
        public IHttpActionResult MyNoticeList(int pageSize = 10, int pageIndex = 1)
        {
            try
            {
                var authInfo = RequestContext.RouteData.Values["auth"] as AuthInfo;

                string strwhere = $" and a.Isdel=0  and  a.recipientId='{authInfo.UserId}' ";
                string sort = " a.createDate desc";
                string fields = " a.*,b.content,b.notifyType ";
                string tablename = " sys_notify a left join sys_notify_content b on a.contentId =b.id  ";
                string primarykey = " a.id ";
                var data = noticeService.GetPageList(strwhere, pageIndex, pageSize, tablename, fields, primarykey, sort);
                var list = data.Items.Select(a => new
                {
                    a.Id,
                    a.NotifyType,
                    isRead = a.Notifystatus,
                    a.CreateDate,
                    a.Content,
                    a.Source,
                    a.SourceId
                });
                return ApiJson(new ApiJsonResult(ApiResult.Success, "", new { list, total = data.TotalNum }));

            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
            }
        }
        /// <summary>
        /// 通知详情
        /// </summary>
        /// <param name="id">通知id</param>
        /// <returns></returns>
        [HttpGet]
        [ApiAuthorize]
        public IHttpActionResult NoticeDetail(int id)
        {
            try
            {
                SysNotifyEntity model = noticeService.GetById(id);
                if (model == null)
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, "未查到对应信息"));
                }
                if (model.ContentId != 0)
                {
                    DataTable dt = noticeService.QueryTable($"select notifyType,content from sys_notify_content where id = {model.ContentId}");
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        model.Content = dt.Rows[0]["content"].ToString();
                        model.NotifyType = ConvertHelper.ToInt32(dt.Rows[0]["notifyType"].ToString()).Value;
                    }
                }
                return ApiJson(new ApiJsonResult(ApiResult.Success, "", model));
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
            }
        }
        /// <summary>
        /// 设置通知为已读
        /// </summary>
        /// <param name="id">通知id</param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize]
        public IHttpActionResult NoticeToRead(int id)
        {
            try
            {
                SysNotifyEntity model = noticeService.GetById(id);
                if (model == null)
                {
                    return ApiJson(new ApiJsonResult(ApiResult.Fail, "未查到对应信息"));
                }

                var ret = noticeService.SetNotifyToRead(id.ToString());

                return ApiJson(new ApiJsonResult(ApiResult.Success, "操作成功"));
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
            }
        }
        /// <summary>
        /// 删除通知
        /// </summary>
        /// <param name="ids">通知id,多个,号隔开</param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize]
        public IHttpActionResult NoticeToDelete(string ids)
        {
            try
            {
                ids = RequestHelper.FilterParam(ids).Trim();

                var ret = noticeService.DeleteNotify(ids);

                return ApiJson(new ApiJsonResult(ApiResult.Success, "操作成功"));
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger("Global").Error(ex);
                return ApiJson(new ApiJsonResult(ApiResult.Fail, ex.Message.ToString()));
            }
        }
    }
}
